/**
 * Created by huotaol on 2017/4/27.
 */
import React, {Component} from "react";
import PropTypes from "prop-types";
import {
    Image,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View
} from "react-native";
import CustomStyle from "../../common/style/CustomStyle";
import {connect} from "react-redux";
import {Actions} from "react-native-router-flux";
import Modal from "react-native-modal";
import AreaSelect from "../page/AreaSelect";
import DatePicker from "react-native-datepicker";
import VerifyCodeButton from "../components/VerifyCodeButton";
import Util from "../main/Util";
import Toast from "react-native-root-toast";
import * as Url from "../constant/Url";
import {request} from "../../common/util/RequestUtil";
import HelpList from "./helplook/component/HelpList";
import * as CommonUtil from "../../common/util/Util";

class SoldCar extends Component {

    // 构造
    constructor(props) {
        super(props);

        // 初始状态
        this.state = {
            isModalVisible: false,
            selectArea: null,
            date: '',
            phone: Util.getUser().phone,
            verifyCode: '',
            requestingVerifyCode: false,
            carDetail: {
                brand: '',
                series: '',
                kind: '',
            },
        };
        this._subscribe = this._subscribe.bind(this);
        this._onCarDetailSelected = this._onCarDetailSelected.bind(this);
    }

    _getSoldCarInfo() {
        const {brand, series, kind} = this.state.carDetail;
        const detail = series + kind;
        return detail ? detail : '车辆信息';
    }

    render() {
        const textList = [];
        textList.push({
            title: '保证爱车最大价值',
            content: `通过国际二手车“行”认证鉴定标准及车行家CIAS专业鉴定流程，让您的车况明明白白，保证您爱车的最大价值。`,
            lineColor: '#ff7200',
        });
        textList.push({
            title: '一站式体验让您轻松卖车',
            content: `车行家帮您找卖家、过户、打款、为您解决所有关于买家的问题，让您足不出户便可轻松卖车。`,
            lineColor: '#ff7200',
        });
        textList.push({
            title: '多种卖车途径更快更高效',
            content: `车行家能让您最短时间卖车最好的价格，只要您在车行家平台卖车，我们就能帮您找到最合适您的卖车方式。`,
            lineColor: '#ffd863',
        });

        const numberTextList = [];
        numberTextList.push({
            number: '01',
            title: '把车放在车行家城市体验中心',
            content: '门店地址：花溪合朋二手车市场\n优势：C2C模式，脱离传统中间环节直接卖给终端客户，价格高\n劣势：时间周期长',
        });
        numberTextList.push({
            number: '02',
            title: '通过车行家网络平台展示帮您找买家',
            content: '优势：脱离传统中间环节直接卖给终端客户，价格偏高'
            + '\n劣势：寄售状态车况随时会有变化，需要复检。'
        });
        numberTextList.push({
            number: '03',
            title: '通过车行家竞价系统帮你找买家',
            content: '优势：时间短，商户竞价选择最高价卖车。'
            + '\n劣势：价格比寄售略低',
        });

        return (
            <View >
                <ScrollView
                    style={{backgroundColor: '#FFC104',}}
                >
                    <Image source={require('../../img/soldCar/title_background.png')}
                           style={{
                               width: CustomStyle.screenWidth, height: CustomStyle.getActualSizeInVertical(428),
                           }}/>
                    <View style={[styles.container]}>

                        <TouchableOpacity style={[styles.itemContainer,]}
                                          onPress={() => {
                                              this.setState({isModalVisible: true});
                                          }}
                        >
                            <Text
                                style={[CustomStyle.baseText, styles.itemText, {}]}>{this.state.selectArea === null ? '请选择地点' : this.state.selectArea.name}</Text>
                        </TouchableOpacity>

                        <TouchableOpacity style={[styles.itemContainer,]} onPress={() => {
                            Actions.BrandRoot({needRequestDetailKind: true, onSelected: this._onCarDetailSelected,});
                        }}>
                            <Text style={[CustomStyle.baseText, styles.itemText, {}]}>{this._getSoldCarInfo()}</Text>
                        </TouchableOpacity>

                        <View style={[styles.itemContainer,]}>
                            <DatePicker
                                mode="date"
                                format="YYYY-MM-DD"
                                date={this.state.date}
                                placeholder='上牌时间'
                                showIcon={false}
                                customStyles={{
                                    dateInput: {
                                        paddingLeft: 0,
                                        alignItems: 'flex-start',
                                        borderWidth: 0,
                                    },
                                    placeholderText: {
                                        fontSize: CustomStyle.getActualFontSize(36),
                                        color: '#b2a682',
                                    },
                                    dateText: {
                                        fontSize: CustomStyle.getActualFontSize(36),
                                        color: '#b2a682',
                                    },
                                    // ... You can check the source to find the other keys.
                                }}
                                onDateChange={(date) => {
                                    this.setState({date: date})
                                }}
                            />
                        </View>

                        <View style={[styles.itemContainer,]}
                        >
                            <TextInput style={[CustomStyle.baseText, styles.itemText, {flex: 1,}]}
                                       keyboardType='numeric'
                                       maxLength={11}
                                       placeholder={'请输入手机号'}
                                       placeholderTextColor={'#b2a682'}
                                       value={this.state.phone}
                                       textAlign="left"
                                       onChangeText={(value) => {
                                           this.setState({phone: value});
                                       }}
                                       underlineColorAndroid={'#00000000'}/>
                        </View>

                        <View style={[styles.itemContainer, {
                            alignItems: 'center',
                            flexDirection: 'row',
                        }]}>
                            <View style={[{
                                flex: 1,
                            }]}>
                                <TextInput style={[CustomStyle.baseText, styles.itemText, {flex: 1}]}
                                           placeholder={'请输入验证码'}
                                           value={this.state.verifyCode}
                                           placeholderTextColor={'#b2a682'}
                                           textAlign="left"
                                           underlineColorAndroid={'#00000000'}
                                           onChangeText={(value) => {
                                               this.setState({verifyCode: value});
                                           }}
                                />
                            </View>

                            <View style={
                                {
                                    width: CustomStyle.getActualSizeInHorizontal(20),
                                    backgroundColor: 'white',
                                    alignSelf: 'stretch'
                                }}>

                            </View>

                            <VerifyCodeButton
                                containerStyle={{
                                    width: CustomStyle.getActualSizeInHorizontal(230),
                                    height: CustomStyle.getActualSizeInVertical(88),
                                    backgroundColor: this.state.requestingVerifyCode ? '#ebebeb' : '#ffc000',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    borderRadius: CustomStyle.getActualSizeInHorizontal(4),
                                }}
                                textStyle={[CustomStyle.baseText, {
                                    fontSize: CustomStyle.getActualFontSize(),
                                    color: 'white',
                                }]}
                                onStart={() => {
                                    this.setState({requestingVerifyCode: true});
                                    this._requestVerifyCode();
                                }}
                                onEnd={() => {
                                    this.setState({requestingVerifyCode: false});
                                }}
                                check={() => {
                                    const phone = this.state.phone;
                                    if (phone && phone.length === 11) {
                                        return true;
                                    } else {
                                        Toast.show("请输入正确手机号", {
                                            duration: Toast.durations.SHORT,
                                            position: Toast.positions.CENTER
                                        });
                                        return false;
                                    }
                                }}
                            />
                        </View>

                        <TouchableOpacity style={{
                            height: CustomStyle.getActualSizeInVertical(88),
                            width: CustomStyle.getActualSizeInHorizontal(530),
                            backgroundColor: '#FF7200',
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginTop: CustomStyle.getActualSizeInVertical(50),
                            marginBottom: CustomStyle.getActualSizeInVertical(30),
                            borderRadius: CustomStyle.getActualSizeInVertical(44),
                            alignSelf: 'center',
                        }}
                                          onPress={() => {
                                              this._subscribe();
                                          }}
                        >
                            <Text style={[CustomStyle.baseText, {
                                fontSize: CustomStyle.getActualFontSize(36),
                                color: 'white',
                            }]}>立即预约</Text>
                        </TouchableOpacity>
                        {textList.map(item => {
                            return <LeftLineText style={{marginTop: CustomStyle.getActualSizeInVertical(20),}}
                                                 lineColor={item.lineColor} content={item.content} title={item.title}/>
                        })}
                        <HelpList title={'车行家怎么帮您找买家'} numberTextList={numberTextList}/>
                    </View>
                </ScrollView>
                <TouchableWithoutFeedback onPress={() => {
                    this.setState({isModalVisible: false});
                }}>
                    <Modal isVisible={this.state.isModalVisible}
                           backdropOpacity={0.65}
                           style={{
                               justifyContent: 'flex-end',
                               margin: 0,
                           }}
                    >
                        <AreaSelect
                            selectArea={this.state.selectArea}
                            onPress={(area) => {
                                this.setState({isModalVisible: false, selectArea: area,});
                            }}/>
                    </Modal>
                </TouchableWithoutFeedback>
            </View>
        );
    }

    /*loc	卖车所在地	是	string
     date	上牌时间  yyyy年MM月	是	string
     phone	手机号	是	string
     code	验证码	是	string
     text	车辆信息文本  品牌+车系+车型	是	string	*/
    _subscribe() {
        const {selectArea, date, phone, verifyCode} = this.state;
        if (selectArea && date && phone && verifyCode) {
            const url = Url.BASE_URL + '/com/reservation_info';
            const param = new FormData();
            param.append('type', 1);
            param.append('loc', selectArea.name);
            param.append('date', date);
            param.append('phone', phone);
            param.append('code', verifyCode);
            param.append('text', this._getSoldCarInfo());
            request(url, 'post', param).then(json => {
                this.setState({
                    selectArea: null,
                    date: '',
                    verifyCode: '',
                    requestingVerifyCode: false,
                    carDetail: {
                        brand: '',
                        series: '',
                        kind: '',
                    },
                });
                Toast.show('预约成功', {
                    duration: Toast.durations.SHORT,
                    position: Toast.positions.CENTER
                });
            }).catch(err => {
                Toast.show(err, {
                    duration: Toast.durations.SHORT,
                    position: Toast.positions.CENTER
                });
            });
        } else {
            CommonUtil.toast('请确认输入全部数据');
        }
    }

    _requestVerifyCode() {
        const url = Url.BASE_URL + '/com/send_verif_code';
        const param = new FormData();
        const {phone} = this.state;
        param.append('phone', phone);
        request(url, 'post', param).then(json => {
            Toast.show('请输入接收到的验证码', {
                duration: Toast.durations.SHORT,
                position: Toast.positions.CENTER
            });
        }).catch(err => {
            Toast.show(err, {
                duration: Toast.durations.SHORT,
                position: Toast.positions.CENTER
            });
        });
    }

    _onCarDetailSelected(brand, series, kind) {
        console.log('SoldCard  ' + `${brand} series ${series} kind ${kind} `);
        this.setState({carDetail: {brand, series, kind}});
    }
}

class LeftLineText extends Component {
    static propTypes = {
        title: PropTypes.string,
        content: PropTypes.string,
        lineColor: PropTypes.any,
    };

    render() {
        return (
            <View style={[this.props.style, {flexDirection: 'row',}]}>
                <View
                    style={{backgroundColor: this.props.lineColor, width: CustomStyle.getActualSizeInHorizontal(10),}}>

                </View>
                <View style={{
                    marginLeft: CustomStyle.getActualSizeInHorizontal(20),
                    marginRight: CustomStyle.getActualSizeInHorizontal(16),
                    marginTop: CustomStyle.getActualSizeInVertical(8),
                    marginBottom: CustomStyle.getActualSizeInVertical(8),
                }}>
                    <Text style={[CustomStyle.baseText, {
                        fontSize: CustomStyle.getActualFontSize(28),
                        color: '#4a3d18',
                    }]}>{this.props.title}</Text>
                    <Text style={[CustomStyle.baseText, {
                        fontSize: CustomStyle.getActualFontSize(24),
                        color: '#857e6e',
                    }]}>{this.props.content}</Text>
                </View>
            </View>
        );
    }
}


const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {};
};

export default connect(mapStateToProps, mapDispatchToProps)(SoldCar);

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'white',
        borderRadius: CustomStyle.getActualSizeInVertical(20),
        marginLeft: CustomStyle.getActualSizeInHorizontal(16),
        marginRight: CustomStyle.getActualSizeInHorizontal(16),
        marginBottom: CustomStyle.getActualSizeInVertical(16),
        paddingBottom: CustomStyle.getActualSizeInVertical(40),
    },
    itemContainer: {
        height: CustomStyle.getActualSizeInVertical(88),
        backgroundColor: '#FFF8D5',
        borderRadius: CustomStyle.getActualSizeInVertical(4),
        marginTop: CustomStyle.getActualSizeInVertical(40),
        flex: 1,
        paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
        marginLeft: CustomStyle.getActualSizeInHorizontal(20),
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: CustomStyle.getActualSizeInHorizontal(20),
    },
    itemText: {
        fontSize: CustomStyle.getActualFontSize(36),
        color: '#b2a682',
    },
});
